<template>
  <section>
    <el-steps :active="stepsNo" finish-status="success" space="30%" align-center style="margin-bottom: 30px">
      <el-step title="基础信息"></el-step>
      <el-step title="具体内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <el-main style="min-height: 300px">
      <el-form ref="form" :model="form" label-width="120px" size="small" v-if="stepsNo === 0">
        <el-form-item label="标题：">
          <el-input size="mini" v-model="form.title" placeholder="请输入标题" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="选择活动类型：">
          <el-select v-model="form.saleTypeId" size="mini" @change="selSaleTypeEvent">
            <el-option v-for="saleType in saleTypeList" :key="saleType.id" :value="saleType.id" :label="saleType.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动起止时间：">
          <el-row>
            <el-col :span="11" style="border: 0px solid crimson">
              <el-date-picker size="mini" v-model="form.start" type="datetime"
                              placeholder="选择开始时间" default-time="12:00:00"
                              format="yyyy-MM-dd HH:mm:ss" value-format="timestamp">
              </el-date-picker>
            </el-col>
            <el-col :span="1">~</el-col>
            <el-col :span="10">
              <el-date-picker size="mini" v-model="form.end" type="datetime"
                              placeholder="选择结束时间" default-time="12:00:00" value-format="timestamp"
                              format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <el-row  v-if="stepsNo === 1">
        <el-form label-width="120px" size="small">
          <el-form-item label="活动类型">{{tlSalesObj.name}}</el-form-item>
          <el-form-item v-for="o in tlSalesObj.vals" :key="o.code" :label="o.name">
            <div class="tlSalesObj-val-box">
              <el-input size="mini" v-model="o.val" :placeholder="o.text"></el-input>
              <span>{{o.text}}</span>
            </div>
          </el-form-item>
          <el-form-item label="选择方式">
            <el-radio v-for="type in selPropTypes" :key="type.val" :label="type" v-model="selPropType" @change="initSelPropType">{{type.name}}</el-radio>
            <el-card v-if="showCard" style="margin-top: 10px;width: 90%">
              <checked-goods-type v-if="selPropType.val===1" :value="tlSalesObj.propertiesValue"/>
              <mall-goods v-if="selPropType.val===3" :value="tlSalesObj.propertiesValue"/>
            </el-card>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row v-if="stepsNo===2" v-loading="true" :element-loading-text="this.form.id?'更新中...':'提交中...'" element-loading-spinner="el-icon-loading"/>
      <el-row v-if="stepsNo===3">
        <icon class="icon" name="check" style="margin-left:43%;margin-top:10px;width:5%;height:5%;color: seagreen"/>
      </el-row>
    </el-main>
    <el-footer>
      <el-button v-if="stepsNo > 0 && stepsNo <=1" size="mini" @click="stepsNo--" type="primary">上一步</el-button>
      <el-button v-if="stepsNo < 1" size="mini" @click="stepsNo++" type="primary">下一步</el-button>
      <el-button v-if="stepsNo === 1" size="mini" @click="confirmFormBtn(form)" type="primary">确认</el-button>
    </el-footer>
  </section>
</template>

<script>
  import mallGoods from '../mallGoods/mallGoods'
  import checkedGoodsType from '../mallGoods/checkedGoodsType'
  import dateFormater from '@/common/date-formater'
  import {mapGetters, mapActions, mapMutations} from 'vuex'
  import errHandler from '@/assets/errHandler.js'
  import Vue from 'vue'//后续添加属性，需要vue联动
  export default {
    name: "newSale",
    components: {checkedGoodsType,mallGoods},
    props:['sale'],
    data() {
      return {
        showCard:false,
        stepsNo:0,
        saleTypeList:null,
        tlSalesObj:{},
        form:{
          saleTypeId:'',
          title:'',
          storeId:null,
          start:'',
          end:'',
          tlSales:null
        },
        selPropTypes:[
          {name:'全店通用',val:5},
          {name:'商品类型可用',val:1},
          {name:'商品可用',val:3},
        ],
        selPropType:null,
        mallGoodsTypeList:null,
      }
    },
    created(){
      if(this.sale){
        console.log(this.sale)
        Vue.set(this.form,'id',this.sale.id)
        this.readyForm()
      }
      this.form.storeId=this.department.id
      this.getSaleTypeList()
    },
    watch:{
      selPropType(nv,ov){
        console.log('进入watch')
        this.mallGoodsTypeList=null
        this.tlSalesObj.propertiesType=nv.val
        if(nv.val === 5){
          this.tlSalesObj.propertiesValue=null
          //加载店铺所有商品，添加到propvalue里，需要loading一下
        }else{
          console.log('到这没？？？')
          //都是部分的，需要跳出新的内容，加载商品类型列表
          this.showCard=true
          // this.getMallGoodsTypeList()
        }
      },
    },
    computed:{
      ...mapGetters(['department']),
    },
    methods: {
      ...mapActions({
        fetch: 'fetch'
      }),
      initSelPropType(e){
        this.showCard=false
        if(e.val===5){
          this.tlSalesObj.propertiesValue=null
        }else {
          this.tlSalesObj.propertiesValue=[]
          console.log('赋[]值')
          setTimeout(()=>{
            this.showCard=true
          },1000)
        }
      },
      readyForm(){
        this.selSaleTypeEvent(this.sale.saleType.id)
        this.selPropType=this.selPropTypes.find(t=>t.val === this.sale.propertiesType)
        console.log('赋值完watch')
        for(let k1 in this.sale){
          for(let k2 in this.form){
            if(k2 === k1){
              this.form[k2]=this.sale[k1]
            }
          }
          this.tlSalesObj.vals.forEach(v=>{
            if(v.code === k1){
              v.val = this.sale[k1]
            }
          })
        }
        this.form.saleTypeId=this.sale.saleType.id
        if(this.sale.propertiesValue){
          let value=[]
          let tmp ='['+ this.sale.propertiesValue +']'
          tmp=JSON.parse(tmp)
          tmp.forEach((t,i)=>{
            this.tlSalesObj.propertiesValue[i]=t
          })
        }else {
          this.tlSalesObj.propertiesValue=null
        }
      },
      look(form){
        console.log(form)
        console.log(this.tlSalesObj)
      },
      getSaleTypeList(){
        this.fetch({name:"getSaleTypeList"})
          .then(res=>{
            this.saleTypeList=res
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      selSaleTypeEvent(e){
        console.log('———————初始化sale的地方—————————',e)
        if(e===1){//满减
          this.tlSalesObj={
            name:'满减',
            vals:[
              {name:'满额',code:'levelFee',val:0},
              {name:'减额',code:'saleFee',val:0}
            ],
            propertiesType:'',
            propertiesValue:[]
          }
        }else if(e === 2){//限时折扣
          this.tlSalesObj={
            name:'限时折扣',
            vals:[
              {name:'折扣率',code:'discountRate',val:1,text:'*请输入0~1之间的小数，保留两位小数'},
              {name:'限购量',code:'limitCount',val:0},
            ],
            propertiesType:'',
            propertiesValue:[]
          }
        }
        console.log('———————初始化sale结束的地方—————————')
      },
      confirmFormBtn(form){
        let tlSales=this.readyTlSales(this.tlSalesObj)
        console.log('—————查看更新时的tlSales———————————',tlSales)
        this.stepsNo =2
        let tmp={...form}
        tmp.start=dateFormater.formatDatetime(form.start)
        tmp.end=dateFormater.formatDatetime(form.end)
        tmp.storeId= this.department.id
        if(form.id){
          //有id，更新
          tmp={...tmp,...tlSales}
          console.log(tmp)
          this.updateSale(tmp)
        }else {
          tmp.tlSale=JSON.stringify(tlSales)
          this.createSale(tmp)
        }
      },
      readyTlSales(obj){
        console.log(obj)
        let tmp={}
        obj.vals.forEach(v=>{
          tmp[v.code]=v.val
        })
        let value=obj.propertiesValue
        if(value){
          value=value.filter( (item, index,self) =>{
            return self.indexOf(item) == index
          })
          value=JSON.stringify(value)
          value=value.replace('[','')
          value=value.replace(']','')
        }
        tmp.propertiesValue=value
        tmp.propertiesType=obj.propertiesType
        return tmp
      },
      updateSale(data){
        console.log('更新啦，看看参数——————————',data)
        this.fetch({name:"updateSale",data})
          .then(res=>{
            console.log('更新成功——————',res)
            this.stepsNo =3
            setTimeout(()=>{
              this.$emit('closeDialog')
            },2000)
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      createSale(data){
        console.log('创建啦，看看参数——————————',data)
        this.fetch({name:"createSale",data})
          .then(res=>{
            console.log('创建成功——————',res)
            this.stepsNo =3
            setTimeout(()=>{
              this.$emit('closeDialog')
            },2000)
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      getMallGoodsTypeList(){
        this.fetch({name:"getMallGoodsTypeList",data:{storeId:this.department.id}})
          .then(res=>{
            console.log(res)
            this.showCard=true
            // this.mallGoodsTypeList=res
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
    }
  }
</script>

<style scoped>
.tlSalesObj-val-box{
  display: flex;
  flex-direction: column;
}
</style>
